package top.xtcoder.xtpsd.log;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
	private static final Integer lock = 1;
	private Class<?> cls;
	private Log(Class<?> cls) {
		this.cls = cls;
	}
	
	public static Log getLog(Class<?> cls) {
		return new Log(cls);
	}
	
	public void log(Throwable e, String msg, Object ...args) {
		consolePrint(e, "Log", msg, args);
	}
	
	public void log(String msg, Object ...args) {
		consolePrint(null, "Log", msg, args);
	}
	
	public void error(Throwable e, String msg, Object ...args) {
		consolePrint(e, "Error", msg, args);
	}
	
	public void error(String msg, Object ...args) {
		consolePrint(null, "Error", msg, args);
	}
	
	public void consolePrint(Throwable e, String type, String msg, Object ...args) {
		synchronized (lock) {
//			StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//			for(int i = 0; i < stackTrace.length; i ++) {
//				System.out.println("stackTrace.method=" + stackTrace[i].getMethodName());
//				System.out.println("stackTrace.filename=" + stackTrace[i].getFileName());
//				System.out.println("stackTrace.className=" + stackTrace[i].getClassName());
//				System.out.println("stackTrace.lineNumber=" + stackTrace[i].getLineNumber());
//			}
			if(args != null && args.length > 0) {
				msg = String.format(msg, args);
			}
			msg = msg.replaceAll("\n", "\n|\t");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			PrintStream out = "error".equals(type.toLowerCase()) ? System.err : System.out;
			out.println("┏━━━━━ " + type + " [" + cls.getSimpleName( ) + " - 起始] ━━━");
			out.println("| 所在位置：" + cls.getName());
			out.println("| 日志时间：" + sdf.format(new Date()));
			out.println("| 日志内容：" + msg);
			if(e != null) {
				out.println("| ");
				out.println("| 异常信息：" + e);
				StackTraceElement[] trace = e.getStackTrace();
				for (StackTraceElement traceElement : trace) {
					out.println("| \t at " + traceElement);
				}
//				e.printStackTrace();
			}
			out.println("┗━━━━━ " + type + " [" + cls.getSimpleName( ) + " - 结束] ━━━\n");
		}
	}
}
